package com.dasoji.ordlist;
import com.dasoji.db.*;
import android.database.sqlite.*;
import android.database.*;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.EditText;
import android.widget.TextView;
import android.media.MediaPlayer;
import android.util.Log;
import android.text.TextWatcher;
import android.text.Editable;
import android.widget.SimpleCursorAdapter.CursorToStringConverter;
import android.net.Uri;
import org.json.*;
import android.widget.* ;
import java.io.*;

public class DictionaryActivity extends ListActivity 
    
{
    private EditText filterText = null ;
    private SimpleCursorAdapter adapter=null ;
    private FilterQueryProvider fqp = null ;
    private ListView lv = null ;   
    
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list_example);
        
        try
        {
            createDatabaseIfRequired();
        }
        catch (Exception e)
        {
            Log.e("EXCEPTION", "ERROR in creating database");
            Toast.makeText(getApplicationContext(),"Error creating database" ,Toast.LENGTH_LONG).show();
        }
        DictionaryOpenHelper doh;
        doh = new DictionaryOpenHelper (this);
        final SQLiteDatabase mydb = doh.getReadableDatabase();
        Cursor v = mydb.query("ordbog", null, "difficulty >= " +Preferences.getDifficulty(), null,null, null,null);
    //    String sarr[] = new String [v.getCount()];
    //    int i=0;
    //    while (v.moveToNext())
    //    {
    //        sarr[i++] = v.getString(0)+ " --- " +v.getString(1);
    //    }
        filterText = (EditText) findViewById(R.id.search_box);
        filterText.addTextChangedListener(filterTextWatcher);

        String [] columns = new String [] {"dansk", "engelsk"};
        int [] to = new int [] {R.id.dansk_entry, R.id.engelsk_entry} ;
        adapter= new SimpleCursorAdapter( this, R.layout.list_example_entry  , v, columns , to);
    setListAdapter(adapter);

    fqp = new FilterQueryProvider()
    {
        public Cursor runQuery(CharSequence constraint)
        {
            Log.d("inside filter", "runQuery constraint:"+constraint);
            Cursor cur = mydb.query("ordbog", null, "dansk like '"+ constraint + "%'" + " and difficulty >= " +Preferences.getDifficulty(), null,null, null,null);
            Log.d("Cursor size is ", ""+ cur.getCount());
            return cur; //now your adapter will have the new filtered content
        }

    };

    adapter.setFilterQueryProvider(fqp);
    lv = getListView();
    lv.setOnItemClickListener( new DanishWordClicked() );

    }

    private class DanishWordClicked implements OnItemClickListener
    {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id)
        {
            CharSequence englishtext = ((TextView) view.findViewById(R.id.engelsk_entry)).getText();
            String danishtext = ((TextView) view.findViewById(R.id.dansk_entry)).getText().toString();
            String dentext= Uri.encode(danishtext);
            Log.v("Prefs", "Printing Pref values "+ Preferences.getPronounce() + Preferences.getMeaning());
            if (Preferences.getPronounce())
            {    
                try
                {
                    MediaPlayer mp =MediaPlayer.create(getApplicationContext(),Uri.parse("http://translate.google.com/translate_tts?tl=da&q="+dentext));
                    mp.start() ;
                }
                catch (Exception e)
                {
                    Toast.makeText(getApplicationContext(),"Error in obtaining pronouncation \n "+ e.getMessage() ,Toast.LENGTH_SHORT).show();
                }
            }
            if (Preferences.getMeaning())
            {
                Toast.makeText(getApplicationContext(),englishtext ,Toast.LENGTH_LONG).show();
            }
        }

    }


    private TextWatcher filterTextWatcher = new TextWatcher()
    {

        public void afterTextChanged(Editable s)
        {
        }

        public void beforeTextChanged(CharSequence s, int start, int count, int after)
        {
        }

        public void onTextChanged(CharSequence s, int start, int before, int count)
        {
            adapter.getFilter().filter(s);
        }

    };
    private void createDatabaseIfRequired () throws Exception
    {
        DataBaseHelper myDbHelper ;
        myDbHelper = new DataBaseHelper(this);
 
        try
        {
       
            myDbHelper.createDataBase();
 
        }
        catch (IOException ioe)
        {
            throw new Exception("Unable to create database",ioe);
        }
        try
        {
 
            myDbHelper.openDataBase();
            myDbHelper.close();
 
        }
        catch(SQLException sqle)
        {
             throw new Exception ("Unable to read or close created database",sqle);
 
        }

    }

   

}

